package com.sf.fy.uav.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.fy.uav.common.awt.JwtUtil;
import com.sf.fy.uav.common.enums.UserCompanyStatusEnum;
import com.sf.fy.uav.common.enums.UserCompanyValidityPeriodTypeEnum;
import com.sf.fy.uav.common.request.firmclient.FirmClientReq;
import com.sf.fy.uav.common.request.user.UserCompanyEditReq;
import com.sf.fy.uav.common.request.user.UserCompanyReq;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.entity.UserCompany;
import com.sf.fy.uav.user.mapper.UserCompanyMapper;
import com.sf.fy.uav.user.mapper.UserMapper;
import com.sf.fy.uav.user.service.IUserCompanyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户额外信息表 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2024-05-31
 */
@Service
public class UserCompanyServiceImpl extends ServiceImpl<UserCompanyMapper, UserCompany> implements IUserCompanyService {

    @Autowired
    private UserCompanyMapper userCompanyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    private static final Integer CONST = 0;

    @Override
    public void add(UserCompanyReq userCompanyReq) {
        this.checkDate(userCompanyReq.getValidityPeriodType(), userCompanyReq.getStartTime(), userCompanyReq.getEndTime());
        String userId = JwtUtil.getUserId();
        Date date = new Date();
        UserCompany userCompany = BeanUtil.copyProperties(userCompanyReq, UserCompany.class);
        userCompany.setCreateTime(date);
        userCompany.setUpdateTime(date);
        userCompany.setEnterpriseId(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 11));
        userCompany.setUserId(userId);
        userCompany.setStatus(UserCompanyStatusEnum.WAITING_FOR_REVIEW.getValue());
        userCompany.setContactPhoneNumber(phoneEncoderUtil.encryptString(userCompanyReq.getContactPhoneNumber()));
        userCompanyMapper.insert(userCompany);
    }

    @Override
    public void edit(UserCompanyEditReq userCompanyEditReq) {
        this.checkDate(userCompanyEditReq.getValidityPeriodType(), userCompanyEditReq.getStartTime(), userCompanyEditReq.getEndTime());
        //校验是否可以编辑
        UserCompany userCompany = userCompanyMapper.selectById(userCompanyEditReq.getId());
        if (ObjectUtils.isEmpty(userCompany)) {
            throw new RuntimeException("关联数据不存在");
        }
        if (!userCompany.getStatus().equals(UserCompanyStatusEnum.REVIEW_REJECTION.getValue())) {
            throw new RuntimeException("不是审核驳回，不能重新编辑");
        }
        String userId = JwtUtil.getUserId();
        if (!userId.equals(userCompany.getUserId())) {
            throw new RuntimeException("非公司关联人，不能重新编辑");
        }
        BeanUtils.copyProperties(userCompanyEditReq, userCompany);
        userCompany.setStatus(UserCompanyStatusEnum.WAITING_FOR_REVIEW.getValue());
        userCompany.setUpdateTime(new Date());
        userCompanyMapper.updateById(userCompany);
    }


    public void checkDate(Byte validityPeriodType, Date startTime, Date endTime) {
        if (validityPeriodType.equals(UserCompanyValidityPeriodTypeEnum.TIME_PERIOD.getValue())) {
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
                throw new RuntimeException("请选择有效时间");
            }
            if (startTime.after(endTime)) {
                throw new RuntimeException("结束时间不能小于开始时间");
            }
        }
    }

    @Override
    public UserCompany getByUserId(String userId) {
        QueryWrapper<UserCompany> userCompanyQueryWrapper = new QueryWrapper<>();
        userCompanyQueryWrapper.eq("user_id", userId);
        UserCompany userCompany = userCompanyMapper.selectOne(userCompanyQueryWrapper);
        if (!ObjectUtils.isEmpty(userCompany)) {
            userCompany.setContactPhoneNumber(phoneEncoderUtil.decryptString(userCompany.getContactPhoneNumber()));
        }
        return userCompany;
    }

    @Override
    public Page<UserCompany> queryFirmClientPageList(FirmClientReq firmClientReq) {
        Set<String> userIdSet = null;
        if (StringUtils.isNotBlank(firmClientReq.getPhoneNumber())) {
            List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("phone_number", firmClientReq.getPhoneNumber()));
            if (!CollectionUtils.isEmpty(userList)) {
                userIdSet = userList.stream().map(User::getId).collect(Collectors.toSet());
            }
        }
        Page<UserCompany> page = new Page<>(firmClientReq.getPage(), firmClientReq.getSize());
        LambdaQueryWrapper<UserCompany> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(firmClientReq.getCompanyName()), UserCompany::getCompanyName, firmClientReq.getCompanyName())
                .eq(!ObjectUtils.isEmpty(firmClientReq.getContactPhoneNumber()), UserCompany::getContactPhoneNumber, firmClientReq.getContactPhoneNumber())
                .in(!CollectionUtils.isEmpty(userIdSet), UserCompany::getUserId, userIdSet)
                .eq(!ObjectUtils.isEmpty(firmClientReq.getStatus()), UserCompany::getStatus, firmClientReq.getStatus())
                .orderByDesc(UserCompany::getCreateTime);
        return userCompanyMapper.selectPage(page, wrapper);
    }

    @Override
    public Rs<Integer> updateFirmClient(FirmClientReq firmClientReq) {
        if (StringUtils.isBlank(firmClientReq.getId())) {
            throw new RuntimeException("企业id不能为空!");
        }
        UserCompany userCompany = BeanUtil.copyProperties(firmClientReq, UserCompany.class);
        Date date = new Date();
        userCompany.setUpdateTime(date);
        int cnt = userCompanyMapper.updateById(userCompany);
        if (cnt > CONST) {
            return Rs.success(cnt);
        } else {
            return Rs.failed();
        }
    }

    @Override
    public Rs<List<UserCompany>> queryFirmByKeyWord(String keyWord) {
        LambdaQueryWrapper<UserCompany> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(keyWord), UserCompany::getCompanyName, keyWord).or().like(StringUtils.isNotBlank(keyWord), UserCompany::getEnterpriseId, keyWord);
        List<UserCompany> userCompanies = userCompanyMapper.selectList(wrapper);
        return Rs.success(userCompanies);
    }
}
